<template>
  <div>
    <el-card class="card" style="height: 80px; margin: 10px 0">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名">
          <el-input placeholder="请输入搜索用户名" v-model="keyWords" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchWords" :disabled="!keyWords"
            >搜索</el-button
          >
          <el-button
            type="primary"
            @click="layoutSetting.refresh = !layoutSetting.refresh"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button
        type="primary"
        @click="batchRemoveRoleUser"
        :disabled="!selectIdArr.length"
        >批量删除</el-button
      >
      <el-table
        border
        style="margin: 20px 0"
        :data="userArr"
        @selection-change="selectChange"
      >
        <el-table-column
          type="selection"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column
          label="#"
          align="center"
          width="60"
          type="index"
        ></el-table-column>
        <el-table-column
          label="ID"
          align="center"
          width="60"
          prop="id"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名字"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="280px" align="center">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="userRole(row)"
              >分类角色</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateUser(row)"
              >编辑</el-button
            >
            <!-- 气泡确认框 -->
            <el-popconfirm
              :title="`你确定要删除${row.username}?`"
              width="260px"
              @confirm="removeRoleUser(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 11]"
        background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @change="getHasUserData"
      />
    </el-card>
    <!-- 抽屉组件  添加｜修改-->
    <el-drawer v-model="show">
      <template #header>
        <h4>{{ userParams.id ? "更新用户" : "添加用户" }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="myFormRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户姓名"
              v-model="userParams.username"
            />
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input placeholder="请输入用户昵称" v-model="userParams.name"
          /></el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请输入用户密码"
              type="password"
              v-model="userParams.password"
          /></el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-drawer>
    <!-- 抽屉组件  分配角色-->
    <el-drawer v-model="drawerShow">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disabled="true" />
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="roleUserArr"
              @change="handleCheckedRoleUserChange"
            >
              <el-checkbox
                v-for="role in allRolesArr"
                :key="role"
                :label="role"
                :value="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="drawerShow = false">cancel</el-button>
        <el-button type="primary" @click="roleSave">confirm</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { defineOptions, ref, onMounted, watch, reactive, nextTick } from "vue";
//引入API
import {
  reqHasUserData,
  reqAddOrUpdateUser,
  reqRoleUserData,
  reqSetRoleUser,
  reqRemoveUser,
  reqBatchRemoveUser,
} from "@/api/acl/user";
//引入ts类型
import type { UserInfo, RoleUser } from "@/api/acl/user/type";
//引入仓库
import useLayoutSettingStore from "@/store/modules/layoutSetting";
import { ElMessage } from "element-plus";
defineOptions({
  name: "User",
});
//应用仓库
let layoutSetting = useLayoutSettingStore();
let currentPage = ref<number>(1); //当前页
let pageSize = ref<number>(3); //当前页有多少数据
let total = ref<number>(0); //总数据
let userArr = ref<UserInfo[]>([]); //用于储存用户分类数据的数组
let show = ref<boolean>(false); //控制抽屉的显示与隐藏
let drawerShow = ref<boolean>(false); //分配角色抽屉的显示与隐藏
let myFormRef = ref(); //获取form组件的实例
let keyWords = ref<string>(""); //搜索关键字
//用户信息的参数收集及初始化
let userParams = reactive<UserInfo>({
  id: "",
  username: "",
  password: "",
  name: "",
});

const checkAll = ref(false); //全选按钮
const isIndeterminate = ref(true); //用于全选按钮切换模式的控制
const roleUserArr = ref<RoleUser[]>([]); //已选用户角色数据
const allRolesArr = ref<RoleUser[]>([]); //所有用户角色数据
let selectIdArr = ref<UserInfo[]>([]);
onMounted(() => {
  getHasUserData();
});
//获取用户分类列表的数据
const getHasUserData = async () => {
  let result = await reqHasUserData(
    currentPage.value,
    pageSize.value,
    keyWords.value
  );
  // console.log(result);
  if (result.code == 200) {
    total.value = result.data.total;
    userArr.value = result.data.records;
  }
};
//监听当前页数据下拉框的改变
watch([pageSize], () => {
  currentPage.value = 1;
});
//添加用户
const addUser = () => {
  //清除数据
  Object.assign(userParams, {
    id: "",
    username: "",
    password: "",
    name: "",
  });
  //清除表单字段的提示
  // myFormRef.value?.resetFields();
  nextTick(() => {
    myFormRef.value.clearValidate();
  });
  show.value = true;
};
//修改用户
const updateUser = (row: UserInfo) => {
  Object.assign(userParams, row);
  //清除表单字段的提示
  // myFormRef.value?.resetFields();
  nextTick(() => {
    myFormRef.value.clearValidate();
  });
  show.value = true;
};
//自定义校验规则的回调
const validatorUsername = (rule: any, value: any, callback: any) => {
  // 正则表达式，匹配至少5个英文小写字母组成的字符串
  const regex = /^[a-z]{5,}$/;
  if (!regex.test(value)) {
    // 如果不匹配，则调用callback并传入错误信息
    callback(new Error("用户姓名必须至少包含5个英文小写字母"));
  } else {
    // 如果匹配，则调用callback而没有参数，表示验证通过
    callback();
  }
};
const validatorName = (rule: any, value: any, callback: any) => {
  // 正则表达式，匹配至少5个英文小写字母组成的字符串
  const regex = /^[a-z]{5,}$/;
  if (!regex.test(value)) {
    // 如果不匹配，则调用callback并传入错误信息
    callback(new Error("用户昵称必须至少包含5个英文小写字母"));
  } else {
    // 如果匹配，则调用callback而没有参数，表示验证通过
    callback();
  }
};
const validatorPassword = (rule: any, value: any, callback: any) => {
  // 正则表达式，匹配至少6个数字组成的字符串
  const regex = /^\d{6,}$/;

  if (!regex.test(value)) {
    // 如果不匹配，则调用callback并传入错误信息
    callback(new Error("密码必须至少包含6个数字"));
  } else {
    // 如果匹配，则调用callback而没有参数，表示验证通过
    callback();
  }
};
//表单校验规则
const rules = reactive({
  username: [{ required: true, trigger: "blur", validator: validatorUsername }],
  name: [{ required: true, trigger: "blur", validator: validatorName }],
  password: [{ required: true, trigger: "blur", validator: validatorPassword }],
});
//取消按钮的回调
const cancel = () => {
  show.value = false;
};
//确定按钮的回调
const save = async () => {
  //保存数据之前确保表单数据完全通过才可以发送请求
  await myFormRef.value.validate();
  let result = await reqAddOrUpdateUser(userParams);
  // console.log(result);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: userParams.id ? "修改成功" : "添加成功",
    });
    show.value = false;
    //添加用户时候页码回到第一页 如果是更新用户则留在当前页
    if (!userParams.id) currentPage.value = 1;
    //再次获取用户分类列表的请求
    // getHasUserData();
    //浏览器自动刷新一次
    window.location.reload();
  } else {
    ElMessage({
      type: "error",
      message: userParams.id ? "修改失败" : "添加失败",
    });
    show.value = false;
  }
};
//点击分类角色按钮的回调
const userRole = async (row: UserInfo) => {
  Object.assign(userParams, row);
  let result = await reqRoleUserData(row.id as number);
  // console.log(result);
  if (result.code == 200) {
    roleUserArr.value = result.data.assignRoles;
    allRolesArr.value = result.data.allRolesList;
    drawerShow.value = true;
  }
};
//全选按钮
const handleCheckAllChange = (value: boolean) => {
  // console.log(value);
  roleUserArr.value = value ? allRolesArr.value : [];
  isIndeterminate.value = false;
};
//用户角色选择的回调
const handleCheckedRoleUserChange = (value: string[]) => {
  // console.log(value);
  //当前已选中的数组与所有用户分类数组长度相等时，全选按钮为全选状态
  checkAll.value = value.length === allRolesArr.value.length;
  ///当前已选中的数组>0&&当前已选中的数组的长度小于所有用户分类数组长度相等时,isIndeterminate设置不确定状态
  isIndeterminate.value =
    value.length > 0 && value.length < allRolesArr.value.length;
};

//分配角色保存按钮的回调
const roleSave = async () => {
  //收集数据
  let data = {
    roleIdList: roleUserArr.value.map((item) => {
      return item.id as number;
    }),
    userId: userParams.id as number,
  };
  console.log(data);
  let result = await reqSetRoleUser(data);
  if (result.code == 200) {
    drawerShow.value = false;
    ElMessage({ type: "success", message: "用户分配职位成功" });
    getHasUserData();
  } else {
    drawerShow.value = false;
    ElMessage({ type: "error", message: "用户分配职位失败" });
  }
};
//收集id数据；当选择项发生变化时会触发该事件
const selectChange = (value: any) => {
  selectIdArr.value = value;
};

//删除用户账号
const removeRoleUser = async (id: number) => {
  let result = await reqRemoveUser(id);
  if (result.code == 200) {
    ElMessage({ type: "success", message: "删除成功" });
    getHasUserData();
  }
};

//批量删除用户账号
const batchRemoveRoleUser = async () => {
  //整理批量删除所需要的ID
  let idList = selectIdArr.value.map((item) => {
    return item.id as number;
  });
  // console.log(idList);
  let result = await reqBatchRemoveUser(idList);
  if (result.code == 200) {
    ElMessage({ type: "success", message: "批量删除成功" });
    getHasUserData();
  } else {
    ElMessage({ type: "error", message: "批量删除失败" });
  }
};

//点击搜索按钮查找关键字
const searchWords = () => {
  getHasUserData();
  keyWords.value = "";
};
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
}
</style>
